<template>
	<view class="box">
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					<text style="color: red; margin-right: 5px;">*</text>模板名称：
				</view>
				<view class="uni-list-cell-db">
					<view class="uni-input">
						<input v-model="form.name" type="text" placeholder="请输入模板名称"
							style="position: relative; top: 5rpx;" />
					</view>
				</view>
			</view>
		</view>
		<!-- 更改资费提示框 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog @confirm="saveAlert()" type="success" title="提示" :content="content"></uni-popup-dialog>
		</uni-popup>
		<view class="charge_title">
			<uni-title title="资费类型"></uni-title>
			<view class="duration_title">
				<text>按时收费价格</text>
				<switch @change="durationChange" color="#4DA7FF" :checked="durationChecked" style="zoom:.8" />
			</view>
		</view>

		<uni-card v-if="durationChecked">
			<view v-for="(item, index) in form.chargeTmplPriceList" :key="index" style="margin-top: 10px!important;">
				<!-- 资费 -->
				<view v-if="item.type == 'DURATION'">
					<input v-model="item.price" type="digit" maxlength="4"
						@input="numberFixedDigit($event,'price',index,form.chargeTmplPriceList)"
						style="margin-right: 10px;" class="costIpt" />
					元，可充电
					<input v-model="item.unit" type="number" maxlength="2" style="margin: 0px 10px;" class="costIpt" />
					小时<text v-if="index!=0" @click="deletePrices(index, item)" class="icon iconfont"
						style="color: #F47576; float: right; position: relative; top: 20rpx;">&#xe601;</text>
					<view class="clear"></view>
				</view>
			</view>
			<view @click="addPrices(index)" style="color: #60AEFF; text-align: center; margin-top: 20px;">
				添加资费
				<text class="icon iconfont" style="margin-left: 5px; position: relative; top: 3rpx;">&#xe600;</text>
			</view>
		</uni-card>
		<!-- <view style="text-align: center;">
			<view @click="addForbidden()" type="default" size="mini"
				style="color: #7F7F7F; background-color: #E5E5E5; width: 85%; height: 70rpx; line-height: 70rpx; margin: 0px auto; border-radius: 20px; border: none!important; padding: 3px 0px; font-size: 14px;">
				添加时段</view>
		</view> -->
		<view class="charge_title">
			<view class="duration_title">
				<text>电费服务费单价</text>
				<switch @change="quantityChange" color="#4DA7FF" :checked="quantityChecked" style="zoom:.8" />
			</view>
		</view>
		<uni-card v-if="quantityChecked">
			<view v-for="(item, index) in form.chargeTmplPriceList" :key="index" style="margin-top: 10px!important;">
				<!-- 资费 -->
				<view v-if="item.type == 'QUANTITY'">
					<view>
						电&nbsp;&nbsp;&nbsp;&nbsp;费：<input v-model="item.price" type="digit" maxlength="4"
							@input="numberFixedDigit($event,'price',index,form.chargeTmplPriceList)"
							style="margin-right: 10px;" class="costIpt" />
						元/kW·h</view>
					<view>
						服务费:<input v-model="item.serviceFee" type="digit" maxlength="4"
							@input="numberFixedDigit($event,'serviceFee',index,form.chargeTmplPriceList)"
							style="margin: 0px 10px;" class="costIpt" max />元/kW·h
					</view>
				</view>
			</view>
		</uni-card>
		<!-- 占仓费 -->
		<view style="padding: 15px 0px 0px 30px; color: #000000; font-size: 16px; font-weight: bold;">
			占仓费
		</view>
		<uni-card style="margin-top: 10px!important;">
			<view class="uni-body" style="font-size: 15px!important; margin-bottom: 10px;">
				<view style="color: #1875D2!important; margin-bottom: 10px;">
					<text style="font-weight: bold;">收费设置</text>
					<text style="float: right; color: #BEBEBE; font-size: 12px;">充电结束后免费占仓时段/资费设置</text>
					<view class="clear"></view>
				</view>
			</view>
			<view style="color: #000000;">
				免费占仓时长：
				<input v-model="form.occupyFreeDuation" type="number" maxlength="2" style="margin: 0px 10px 0px 5px;"
					class="costIpt" />
				小时
			</view>
			<view style="color: #000000;">
				超出收费：
				<input v-model="form.occupyChargePrice" type="digit" maxlength="4"
					@input="numberFixedDigit($event,'occupyChargePrice')" style="margin: 0px 10px 0px 5px;"
					class="costIpt" />
				元&nbsp;/
				<input v-model="form.occupyChargeDuration" type="number" maxlength="2"
					style="margin: 0px 10px 0px 10px;" class="costIpt" />
				小时
			</view>
			<view style="color: #000000;">
				收费上限：
				<input v-model="form.occupyChargeUpperLimit" type="digit"
					@input="numberFixedDigit($event,'occupyChargeUpperLimit')" maxlength="4"
					style="margin: 0px 10px 0px 5px;" class="costIpt" />
				元
			</view>
			<view class="uni-body" style="font-size: 15px!important; margin-top: 20px;">
				<view style="color: #1875D2!important; margin-bottom: 10px;">
					<text style="font-weight: bold;">免费占仓时段设置</text>
					<text style="float: right; color: #BEBEBE; font-size: 12px;">若不设置，默认无免费占仓时段</text>
					<view class="clear"></view>
				</view>
				<view style="color: #000000;">
					<picker style="display: inline-block; margin-right: 20px;" mode="multiSelector"
						@change="freeStartChange($event, item, index)" :value="form.occupyFreeStartTimeArrey"
						:range="freeTimeOptions">
						<view class="uni-input" v-if="form.occupyFreeStartTime"
							style="color: #000000!important; border-bottom: 1px solid #E5E5E5; text-align: center; padding: 5rpx 60rpx 8rpx 10rpx; display: inline-block;">
							{{form.occupyFreeStartTime}}
						</view>
						<view class="uni-input" v-else
							style="color: #BEBEBE;font-size:24rpx;border-bottom: 1px solid #E5E5E5;">
							选择开始时间
						</view>
					</picker>
					至
					<picker style="display: inline-block; margin-left: 20px;" mode="multiSelector"
						@change="freeEndChange($event, item, index)" :value="form.occupyFreeEndTimeArrey"
						:range="freeTimeOptions">
						<view class="uni-input" v-if="form.occupyFreeEndTime"
							style="color: #000000!important; border-bottom: 1px solid #E5E5E5; text-align: center; padding: 5rpx 10rpx 8rpx 60rpx; display: inline-block;">
							{{form.occupyFreeEndTime}}
						</view>
						<view class="uni-input" v-else
							style="color: #BEBEBE;font-size:24rpx;border-bottom: 1px solid #E5E5E5;">
							选择结束时间
						</view>
					</picker>
					<uni-icons type="clear" size="20" color="#666666" v-if="form.occupyFreeStartTime || form.occupyFreeEndTime" @click="clearOccupyTime"></uni-icons>

				</view>
			</view>
		</uni-card>
		<view style="padding: 10px 4%; text-align: center;">
			<button :loading="saveLoading" @click="save()" type="primary" size="mini"
				style="margin-right: 20rpx; background-color: #4DA7FF; width: 48%; height: 80rpx; line-height: 80rpx;">保存</button>
			<button @click="back()" type="primary" size="mini"
				style="background-color: #C2C2C2; width: 48%; height: 80rpx; line-height: 80rpx;">取消</button>
		</view>
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import {
		chargeTmpl
	} from '@/api/equip.js';
	import mainjs from '@/common/main.js';
	export default {
		mixins: [mainjs],
		data() {
			return {
				form: {
					name: '',
					organizationId: '',
					occupyChargeDuration: '',
					occupyChargeUpperLimit: '',
					occupyChargePrice: '',
					occupyFreeDuation: '',
					occupyFreeStartTime: null,
					occupyFreeEndTime: null,
					promptDesc: '暂无',
					attentionDesc: '暂无',
					chargeTmplPriceList: [{
							type: 'DURATION',
							price: '',
							unit: '',
							serviceFee: '0',
						},
						{
							type: 'QUANTITY',
							price: '',
							serviceFee: '', //服务费
							unit: '1', //充电时间 按次/按量传1
						},
					],

				},
				chinaBox: ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七',
					'十八', '十九', '二十', '二一', '二二', '二三', '二四'
				],
				timeOptions: [
					['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15',
						'16', '17', '18', '19', '20', '21', '22', '23'
					],
				],
				freeTimeOptions: [
					['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15',
						'16', '17', '18', '19', '20', '21', '22', '23'
					],
					['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15',
						'16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31',
						'32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47',
						'48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59'
					],
					['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15',
						'16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31',
						'32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47',
						'48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59'
					]
				],
				msgType: '',
				messageText: '',
				saveLoading: false,

				chargeTmplId: '', //资费模板id
				durationChecked: true,
				quantityChecked: true,
				content: '确定要新增资费模板吗？',
				isCopy: false, //是否是复制功能
				domainDelList: [], //需删除的收费list

			}
		},
		computed: {
			...mapState(['userinfo'])
		},

		onLoad(option) {
			this.chargeTmplId = option.chargeTmplId;
			this.isCopy = option.isCopy;
			if (this.chargeTmplId) { //编辑
				this.getCost();
				this.form.id = this.chargeTmplId;
				this.content = '更改后充电柜将更新为新的资费模式进行运营，正在进行中的订单按原收费模式计费。确认更改？'
			}
			if (this.isCopy) {
				this.content = '确定要复制该资费模板吗？';
			}
		},
		created() {
			this.$store.dispatch("updateUserInfo");
		},
		methods: {
			numberFixedDigit(e, type, index, obj) {
				// 固定两位小数
				if (Number(e.target.value) > 100) {
					e.target.value = 100
				}
				this.$nextTick(() => {
					if (index != undefined) {
						obj[index][type] = e.target.value;
					} else {
						this.form[type] = e.target.value;
					}
				})
			},
			durationChange(e) {
				let flist = this.form.chargeTmplPriceList.filter(item => item.type == '按时' || item.type == 'DURATION');
				if (e.detail.value && flist.length == 0) {
					let param = {
						type: 'DURATION',
						price: '',
						unit: '',
						serviceFee: '0',
					};
					if (this.form.id) {
						param.logicDelete = 0;
					}
					this.form.chargeTmplPriceList.unshift(param);
				}
				this.durationChecked = !this.durationChecked;
				if (!this.durationChecked) {
					this.quantityChecked = true;
				}
				// if (!e.detail.value) { //关闭 移除数据
				// 	this.form.chargeTmplPriceList = this.form.chargeTmplPriceList.filter(item => item.type == '按量' || item
				// 		.type == 'QUANTITY');
				// }
			},
			quantityChange(e) {
				let flist = this.form.chargeTmplPriceList.filter(item => item.type == '按量' || item.type == 'QUANTITY');
				if (e.detail.value && flist.length == 0) {
					let param = {
						type: 'QUANTITY',
						price: '',
						serviceFee: '', //服务费
						unit: '1', //充电时间 按次/按量传1
					}
					if (this.form.id) {
						param.logicDelete = 0;
					}
					this.form.chargeTmplPriceList.push(param);
				}
				this.quantityChecked = !this.quantityChecked;
				if (!this.quantityChecked) {
					this.durationChecked = true;
					let flist = this.form.chargeTmplPriceList.filter(item => item.type == '按时' || item.type == 'DURATION');
					let durations = {
						type: 'DURATION',
						price: '',
						unit: '',
						serviceFee: '0',
					};

					if (this.form.id) {
						duration.logicDelete = 0;
					}
					if (flist.length == 0) {
						this.form.chargeTmplPriceList.unshift(durations);
					}
				}
				// if (!e.detail.value) { //关闭 移除数据
				// 	this.form.chargeTmplPriceList = this.form.chargeTmplPriceList.filter(item => item.type == '按时' || item
				// 		.type == 'DURATION');
				// }
			},
			// 获取资费模板
			getCost() {
				chargeTmpl('/getChargeTmplById', 'get', {
					id: this.chargeTmplId
				}).then(res => {
					let datas = res.data;
					datas.chargeTmplPriceList.forEach(item => {
						item.type = (item.type == '按量' || item.type == 'QUANTITY') ? 'QUANTITY' :
							'DURATION';
					})
					this.form = datas;
					let duration = this.form.chargeTmplPriceList.filter(item => item.type == 'DURATION');
					let quantity = this.form.chargeTmplPriceList.filter(item => item.type == 'QUANTITY');
					this.durationChecked = duration.length > 0 ? true : false;
					this.quantityChecked = quantity.length > 0 ? true : false;

					if (this.isCopy) {
						delete this.form.id;
					}
				})
			},
			// 解析为uniapp pick组件所需格式
			returnPick() {
				for (let i = 0; i < this.form.chargeIntervalsByTime.length; i++) {
					this.$set(this.form.chargeIntervalsByTime[i], 'startTimeArrey', this.form.chargeIntervalsByTime[i]
						.startTime.split(':'));
					this.$set(this.form.chargeIntervalsByTime[i], 'endTimeArrey', this.form.chargeIntervalsByTime[i]
						.endTime.split(':'));
				}
				this.$set(this.form, 'occupyFreeStartTimeArrey', this.form.occupyFreeStartTime.split(':'));
				this.$set(this.form, 'occupyFreeEndTimeArrey', this.form.occupyFreeEndTime.split(':'));
			},
			// 时段选择起止
			startChange: function(e, item, index) {
				this.index = e.target.value;
				this.form.chargeIntervalsByTime[index].startTime = `${this.timeOptions[0][this.index[0]]}:00:00`;
				item.startTime = this.form.chargeIntervalsByTime[index].startTime;
			},
			endChange: function(e, item, index) {
				this.index = e.target.value;
				this.form.chargeIntervalsByTime[index].endTime = `${this.timeOptions[0][this.index[0]]}:59:59`;
				item.endTime = this.form.chargeIntervalsByTime[index].endTime;
			},
			// 添加时段
			addForbidden() {
				if (this.form.chargeIntervalsByTime[this.form.chargeIntervalsByTime.length - 1].endTime === '23:59:59') {
					this.msgType = 'error';
					this.messageText = `已够24小时`
					this.$refs.message.open()
				} else {
					if (this.form.chargeIntervalsByTime.length > 23) {
						this.msgType = 'error';
						this.messageText = `最多添加24个时段`
						this.$refs.message.open()
					} else {
						this.form.chargeIntervalsByTime.push({
							startTime: this.PrefixInteger(Number(this.form.chargeIntervalsByTime[this.form
								.chargeIntervalsByTime.length - 1].endTime.slice(0, 2)) + 1, 2) + ':00:00',
							endTime: this.PrefixInteger(Number(this.form.chargeIntervalsByTime[this.form
								.chargeIntervalsByTime.length - 1].endTime.slice(0, 2)) + 1, 2) + ':59:59',
							chargeWay: 1,
							chargeIntervalPrices: [{
								cost: '',
								unitVolume: ''
							}]
						});
					}
				}
			},
			// 数字自动补零
			PrefixInteger(num, n) {
				return (Array(n).join(0) + num).slice(-n);
			},
			// 删除时段
			deleteTimes(index) {
				if (this.form.chargeIntervalsByTime.length <= 1) {
					this.msgType = 'error';
					this.messageText = `至少保留一个时段`
					this.$refs.message.open()
				} else {
					this.form.chargeIntervalsByTime.splice(index, 1);
				}
			},
			// 添加时段资费
			addPrices(index) {
				let param = {
					price: '',
					unit: '',
					serviceFee: "0",
					type: 'DURATION'
				};
				if (this.form.id) {
					param.logicDelete = 0;
				}
				this.form.chargeTmplPriceList.push(param);
			},
			// 删除资费
			deletePrices(index, item) {
				this.domainDelList.push(this.form.chargeTmplPriceList[index]);

				this.domainDelList.forEach((item) => {
					item.logicDelete = 1;
				});
				this.form.chargeTmplPriceList.splice(index, 1);
			},
			// 免费时段起止
			freeStartChange: function(e, item, index) {
				this.index = e.target.value;
				this.form.occupyFreeStartTime =
					`${this.freeTimeOptions[0][this.index[0]]}:${this.freeTimeOptions[1][this.index[1]]}:${this.freeTimeOptions[2][this.index[2]]}`;
				// item.occupyFreeStartTime = this.form.occupyFreeStartTime;
			},
			freeEndChange: function(e, item, index) {
				this.index = e.target.value;
				this.form.occupyFreeEndTime =
					`${this.freeTimeOptions[0][this.index[0]]}:${this.freeTimeOptions[1][this.index[1]]}:${this.freeTimeOptions[2][this.index[2]]}`;
				// item.occupyFreeEndTime = this.form.occupyFreeEndTime;
			},
			// 清空时间
			clearOccupyTime() {
				this.form.occupyFreeStartTime = null;
				this.form.occupyFreeEndTime = null;
			},
			// 保存修改
			save() {
				let pattern = /^\d+.?\d{0,2}$/;
				let isTimeCheck = this.compareTime(this.form.occupyFreeStartTime, this.form.occupyFreeEndTime);
				let chargetml = this.form.chargeTmplPriceList.filter(item => (this.durationChecked && item.type ==
						'DURATION' && item.price == '') ||
					(this.quantityChecked && this.durationChecked && item.price == '')
				);
				let quantitytml = this.form.chargeTmplPriceList.filter(item =>
					(this.quantityChecked && item.type == 'QUANTITY' && (item.price == '' || item.serviceFee == ''))
				);
				if (this.form.name === '') {
					this.msgType = 'error';
					this.messageText = `模板名称不能为空`
					this.$refs.message.open()
					return;
				}
				if (chargetml.length > 0) {
					this.msgType = 'error';
					this.messageText = `请输入资费价格信息`
					this.$refs.message.open()
					return;
				}
				if (quantitytml.length > 0) {
					this.msgType = 'error';
					this.messageText = `请输入电费服务费价格信息`
					this.$refs.message.open()
					return;
				}
				// 表单验证
				if (this.form.occupyFreeDuation === '') {
					this.msgType = 'error';
					this.messageText = `免费占仓时长不能为空`
					this.$refs.message.open()
					return;
				} else if (this.form.occupyChargePrice === '') {
					this.msgType = 'error';
					this.messageText = `超出收费不能为空`
					this.$refs.message.open()
					return;
				} else if (!pattern.test(this.form.occupyChargePrice)) {
					this.msgType = 'error';
					this.messageText = `超出收费最多精确到分`
					this.$refs.message.open()
					return;
				} else if (this.form.occupyChargeDuration === '') {
					this.msgType = 'error';
					this.messageText = `超出收费不能为空`
					this.$refs.message.open()
					return;
				} else if (this.form.occupyChargeUpperLimit === '') {
					this.msgType = 'error';
					this.messageText = `收费上限不能为空`
					this.$refs.message.open()
					return;
				} else if (!pattern.test(this.form.occupyChargeUpperLimit)) {
					this.msgType = 'error';
					this.messageText = `收费上限最多精确到分`
					this.$refs.message.open()
					return;
				} else if ((this.form.occupyFreeStartTime || this.form.occupyFreeEndTime) && (!this.form
						.occupyFreeStartTime || !this.form.occupyFreeEndTime)) {
					this.msgType = 'error';
					this.messageText = `请设置免费占仓时段`
					this.$refs.message.open()
					return;
				} else {
					this.$refs.alertDialog.open();
				}
			},
			saveAlert() {
				this.$Toast.loading('加载中');

				let url = this.form.id ? '/updateChargeTmpl' : '/insertChargeTmpl';
				let method = this.form.id ? 'put' : 'post';
				this.form.organizationId = this.userinfo.organizationId;
				let editParam = {
					...this.form
				};
				editParam.chargeTmplPriceList.forEach(item => {
					if (item.type == '按时') {
						item.type = 'DURATION';
					}
					if (item.type == '按量') {
						item.type = 'QUANTITY';
					}
				})
				if (this.form.id) { //编辑
					let chargeList = editParam.chargeTmplPriceList;

					chargeList.forEach((item) => {
						if (item.id) item.logicDelete = 0;

						if (!this.durationChecked && (item.type == 'DURATION' || item.type == '按时')) {
							if (item.id) item.logicDelete = 1;
						}
						if (!this.quantityChecked && (item.type == 'QUANTITY' || item.type == '按量')) {
							if (item.id) item.logicDelete = 1;
						}
					});
					// feeChecked: true, //收费方式 按时
					// quantityChecked: true, //收费方式 按量

					chargeList = chargeList.concat(this.domainDelList);

					editParam.chargeTmplPriceList = chargeList;
				} else { //新增
					if (!this.durationChecked) {
						let checkCharge = editParam.chargeTmplPriceList.filter(item => item.type == 'QUANTITY');
						editParam.chargeTmplPriceList = checkCharge;
					}
					if (!this.quantityChecked) {
						let checkCharge = editParam.chargeTmplPriceList.filter(item => item.type == 'DURATION');
						editParam.chargeTmplPriceList = checkCharge;
					}
				}

				let dataParams = this.detealParam(editParam);
				
				chargeTmpl(url, method, dataParams).then(res => {
					if (res.code == 200) {
						this.$Toast.success(res.message);
						setTimeout(() => {
							this.goback();
						}, 1500)
					}
				}).catch(err => {
					uni.hideLoading();
				});
			},
			detealParam(param) {
				let {
					name,
					organizationId,
					occupyChargeDuration,
					occupyChargeUpperLimit,
					occupyChargePrice,
					occupyFreeDuation,
					occupyFreeStartTime,
					occupyFreeEndTime,
					promptDesc,
					attentionDesc,
					chargeTmplPriceList,
				} = {
					...param
				};
				let datas = {
					name,
					organizationId,
					occupyChargeDuration,
					occupyChargeUpperLimit,
					occupyChargePrice,
					occupyFreeDuation,
					occupyFreeStartTime,
					occupyFreeEndTime,
					promptDesc,
					attentionDesc,
					chargeTmplPriceList,
				};
				if (this.form.id && !this.isCopy) {
					datas.id = this.form.id;
				}
				return datas;
			},
			// 返回
			back() {
				let pages = getCurrentPages(); // 当前页面
				let beforePage = pages[pages.length - 2]; // 上一页
				uni.navigateBack({
					success: function() {
						beforePage.onLoad(); // 执行上一页的onLoad方法
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/css/common.scss";

	.listBtn {
		width: 250rpx;
		height: 60rpx;
		line-height: 60rpx;
		float: left;
		text-align: center;
		color: #FFFFFF;
		background-color: #4DA7FF;
		border-radius: 5px;
	}

	.costIpt {
		width: 120rpx;
		height: 50rpx;
		display: inline-block;
		background-color: #EFF8FF;
		text-align: center;
		position: relative;
		top: 17rpx;
	}

	/deep/ button::after {
		border: none;
	}

	.charge_title {
		padding: 20rpx 30rpx 0 30rpx;

		.duration_title {
			@include flexLayout(center, space-between);
		}
	}

	/deep/ .uni-title__base {
		color: #000000 !important;
		font-weight: bold !important;
		font-size: 32rpx;
	}
</style>
